<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>1205_updating-生命周期(新)</title>
</head>

<body>
  <div id="test"></div>
  <!-- react核心库 -->
  <script type="text/javascript" src="../js/17.0.1/react.development.js"></script>
  <!-- 用于支持react操作DOM -->
  <script type="text/javascript" src="../js/17.0.1/react-dom.development.js"></script>
  <!-- 用于将jsx转为js -->
  <script type="text/javascript" src="../js/17.0.1/babel.min.js"></script>

  <script type="text/babel">

    /**
     * 创建组件
     *  生命周期函数：生命周期钩子函数
     */
    class Count extends React.Component {
      constructor(props) {
        console.log('Count === constructor');
        super(props)
        // 初始化状态
        this.state = {
          count: 1 // 计数
        }
      }


      /**
       * +1
       */
      add = () => {
        this.setState({count: this.state.count + 1})
      }

      /**
       * 不更新状态，强制更新
       */
      force = () => {
        console.log('Count ==== forceUpate');
        this.forceUpdate()
      }



      /**
       * 卸载组件
       */
       remove = () => {
        ReactDOM.unmountComponentAtNode(document.getElementById('test'))
      }

      /**
      * 获取从props派生的state
      */ 
      static getDerivedStateFromProps(props, state) {
        console.log('Count ==== getDerivedStateFromProps');
        console.log(props, '----', state);
        return null
        // return props
      }

      /**
       * 组件挂载完毕
       */
      componentDidMount() {
        console.log('Count === componentDidMount');
      }
      
      /**
       * 组件是否应该被更新
       */
      shouldComponentUpdate(nextProps, nextState) {
        console.log('count === shouldComponentUpdate :', nextProps, '----', nextState);
        return true;
      }

      /**
       * 获取更新前的快照
       */ 
       getSnapshotBeforeUpdate(prevProps, prevState) {
        console.log('Count ==== getSnapshotBeforeUpdate');
        console.log(prevProps, '----', prevState);
        return '你好呀';
      }

      /**
       * 组件更新之后
       */
       componentDidUpdate(prevProps, prevState, snapshot) {
        console.log('count === componentDidUpdate :', prevProps, '----', prevState);
        console.log('snapshot: ', snapshot);
      }

      /**
       * 组件卸载之前
       */
      componentWillUnmount() {
        console.log('Count === componentWillUnmount');
      }

      /**
       * 初始化渲染，状态更新重新渲染
       */
      render() {
        console.log('Count === render');
        const { count } = this.state
        return (
          <div>
            <h2>当前计数：{count}</h2><br />
            <button onClick={this.add}>点我+1</button><br/>
            <button onClick={this.force}>不更改状态强制更新</button>
            </div>
        )
      }
    }

    // 2.渲染虚拟DOM到页面
    ReactDOM.render(<Count count={99}/>, document.getElementById('test'))

  </script>
</body>

</html>